package com.github.bobjoy.java.thread;

/**
 * 多线程同步锁synchronized（全局锁，对象锁）
 * https://blog.csdn.net/jintiaozhuang/article/details/54927238
 */
public class SynchronizedDemo {

    public static void main(String[] args) {
        Sync sync = new Sync();
        for (int i=0; i< 3; i++) {
            new Thread(() -> {
//                sync1.test1();

                Sync sync2 = new Sync();
                sync2.test3();
            }).start();
        }
    }

}

class Sync extends T {

    /**
     * 对象锁：锁住方法
     */
    public synchronized void test1() {
        System.out.println("started");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("ended");
    }

    /**
     * 对象锁：减小锁的粒度，锁住代码段；
     */
    public void test2( ) {
        synchronized (this) {
            System.out.println("started");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("ended");
        }
    }

    /**
     * 全局锁
     */
    public void test3( ) {
        synchronized (Sync.class) {
            System.out.println("started");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("ended");
        }
    }

    @Override
    public void test() {
        super.test();
    }
}

class T {
    public synchronized void test() {

    }
}